package org.example.chat.exception;

import lombok.extern.slf4j.Slf4j;
import org.example.chat.api.CommonResult;
import org.example.chat.validate.ValidateUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;


/**
 * 全局异常处理器
 * @author cheval
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BadCredentialsException.class)
    public CommonResult<String> badCredentialsExceptionHandler(BadCredentialsException exception) {
        return CommonResult.fail(exception.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<Map<String,String>> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errMsg = ValidateUtils.getValidationErrMsg(bindingResult);
        return CommonResult.validateFail(errMsg);
    }
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public CommonResult<Map<String,String>> missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException e) {
        return CommonResult.fail(e.getMessage());
    }

    @ExceptionHandler(RequestLimitedException.class)
    public CommonResult<String> requestLimitedExceptionHandler(RequestLimitedException exception) {
        return CommonResult.fail(exception.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult<String> unknownExceptionHandler(Exception exception) {
        exception.printStackTrace();
        return CommonResult.fail("系统错误");
    }
}
